﻿<%@ WebHandler Language="C#" Class="ShowListIntentMoney" %>

using System;
using System.Web;
using System.Text;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;
using Chenxin.Lib.Hr;
using System.Collections.Generic;

public class ShowListIntentMoney : AjaxHandlerBase
{
    /// <summary>
    /// 基本权限项
    /// </summary>
    public ShowListIntentMoney()
    {
        //意向金作废
        htTypePermit.Add("moneycancel", Constants.Permit_Money_Cancel);
        //意向金确认款项
        htTypePermit.Add("moneycheck", Constants.Permit_Money_Check);
        //意向金反确认
        htTypePermit.Add("checkcancel", Constants.Permit_Money_UnCheck);
        //意向金代保管
        htTypePermit.Add("moneykeep", Constants.Permit_Money_Keep);
        //转移作废
        htTypePermit.Add("cancelmove", Constants.Permit_Money_CancelMove);
        //意向金复核
        htTypePermit.Add("checkagain", Constants.Permit_Money_CheckAgain);
        //意向金反复核
        htTypePermit.Add("checkagaincancel", Constants.Permit_Money_UnCheckAgain);
        //导出
        htTypePermit.Add("export", Constants.Permit_IntentMoney_Export);  
    }

    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        string strOp = context.Request["op"];
        switch (strOp.ToLower())
        {
            case "getlist":
                GetList(context);
                break;
            case "cancelmove": //作废单据
                MoneyCancel(context);
                break;
            case "moneycheck":  //意向金确认入账
                MoneyCheck(context);
                break;
            case "moneykeep":   //确认代保管
                MoneyKeep(context);
                break;
            case "getcancel":   //得到意向金作废实体
                GetCancel(context);
                break;
            case "checkcancel":   //得到意向金反确认
                CheckCancel(context);
                break;
            case "checkagain":   //得到意向金复核
                CheckAgain(context);
                break;
            case "checkagaincancel":   //得到意向金反复核
                CheckAgainCancel(context);
                break;
            default:
                break;
        }
    }
    
    //意向金复核
    private void CheckAgain(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo info = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));

            if (info.IsReview)
            {
                context.Response.Write("{success:'0',msg:'该记录已复核，不能重复复核!',data:''}");
                return;
            }
            if (!info.IsConfirmed)
            {
                context.Response.Write("{success:'0',msg:'该记录未确认，请先进行确认!',data:''}");
                return;
            }
            info.IsReview = true;
            info.UpdateTime = info.ReviewDate = DateTime.Now;
            info.UpdateEmployee = info.ReviewEmployee = CurrentUserInfo.UserName;
            info.UpdateEmployeeId = info.ReviewEmployeeId = CurrentUserInfo.UserId;
            Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.Update(info);
            context.Response.Write("{success:'1',msg:'复核成功!',data:''}");
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    //意向金反复核
    private void CheckAgainCancel(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo info = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));

            if (!info.IsReview)
            {
                context.Response.Write("{success:'0',msg:'该记录未复核，请先进行复核!',data:''}");
                return;
            }
            info.IsReview = false;
            info.UpdateTime = DateTime.Now;
            info.UpdateEmployee = CurrentUserInfo.UserName;
            info.UpdateEmployeeId = CurrentUserInfo.UserId;
            info.ReviewEmployeeId = Guid.Empty;
            info.ReviewEmployee = "";
            info.ReviewDate = null;
            Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.Update(info);
            context.Response.Write("{success:'1',msg:'反复核成功!',data:''}");
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }
    
    //意向金反确认
    private void CheckCancel(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo info = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));

            if (info.IsReview)
            {
                context.Response.Write("{success:'0',msg:'该记录已复核，不能进行反确认!',data:''}");
                return;
            }
            
            info.IsConfirmed = false;
            info.ConfirmDate = null;
            info.ConfirmEmployee = "";
            info.ConfirmEmployeeId = Guid.Empty;
            info.UpdateTime = DateTime.Now;
            info.UpdateEmployee = CurrentUserInfo.UserName;
            info.UpdateEmployeeId = CurrentUserInfo.UserId;

            Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.Update(info);

            context.Response.Write("{success:'1',msg:'反确认成功!',data:''}");
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }
    
    
    //确认意向金代保管
    private void MoneyKeep(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];

            Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo getinfo = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));
            if (getinfo.InOrOut != 0)
            {
                context.Response.Write("{success:'0',msg:'该记录非转移单据，不可代保管!',data:''}");
                return;
            }
            if (getinfo.bCustody == 10)
            {
                context.Response.Write("{success:'0',msg:'该记录已代保管，不可再执行代保管操作!',data:''}");
                return;
            }
            getinfo.bCustody = 10;
            getinfo.UpdateEmployee = CurrentUserInfo.UserName;
            getinfo.UpdateEmployeeId = CurrentUserInfo.UserId;
            getinfo.UpdateTime = DateTime.Now;

            Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.Update(getinfo);
            context.Response.Write("{success:'1',msg:'确认代保管成功!',data:''}");   
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, "")); 
        }
    }
    

    //意向金确认入账
    private void MoneyCheck(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo info = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));
            if (info.IsConfirmed)
            {
                context.Response.Write("{success:'0',msg:'该单据已确认，不能重复确认!',data:''}");
                return;
            }
            info.IsConfirmed = true;
            info.ConfirmDate = info.UpdateTime = DateTime.Now;
            info.ConfirmEmployee = info.UpdateEmployee = CurrentUserInfo.UserName;
            info.ConfirmEmployeeId = info.UpdateEmployeeId = CurrentUserInfo.UserId;

            Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.Update(info);

            context.Response.Write("{success:'1',msg:'确认成功!',data:''}");   
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));            
        }
    }
    
    
    //意向金作废操作
    private void MoneyCancel(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            
            //得到意向金今本信息
            Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo getinfo = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));

            if (getinfo.Status == -1)
            {
                context.Response.Write("{success:'0',msg:'该单据已作废，不可执行作废单据!',data:''}");
                return;
            }

            if (getinfo.IsConfirmed)
            {
                context.Response.Write("{success:'0',msg:'该单据已确认，不可执行作废单据!',data:''}");
                return;
            }

            Chenxin.Lib.Business.Entity.t_Intention_BaseInfo baseinfo = Chenxin.Lib.Business.DAL.t_Intention_BaseInfo.GetModel(getinfo.IntentionId);

            if (getinfo.InOrOut == 1)
                baseinfo.GetedMoney = baseinfo.GetedMoney - getinfo.GetedMoney;
            else
                baseinfo.DeliveredMoney = baseinfo.DeliveredMoney - getinfo.GetedMoney;
            
            getinfo.Status = -1;
            getinfo.UpdateEmployee = getinfo.DeleteEmp =baseinfo.UpdateEmp = CurrentUserInfo.UserName;
            getinfo.UpdateEmployeeId = getinfo.DeleteEmpId =baseinfo.UpdateEmpId = CurrentUserInfo.UserId;
            getinfo.DeleteTime = getinfo.UpdateTime = baseinfo.UpdateTime = DateTime.Now;
            getinfo.DeleteReason = context.Request.Params["DeleteReason"];

            Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.Update(getinfo);
            Chenxin.Lib.Business.DAL.t_Intention_BaseInfo.Update(baseinfo);

            context.Response.Write("{success:'1',msg:'作废成功!',data:''}");        
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    //得到意向金作废实体
    private void GetCancel(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];

            Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo info = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));
            if (info == null)
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "该意向金不存在！"));
                return;
            }
            Chenxin.Lib.Business.Entity.t_Intention_BaseInfo baseinfo = Chenxin.Lib.Business.DAL.t_Intention_BaseInfo.GetBillInfo(info.IntentionId);

            context.Response.Write(string.Format("{{success:'1',msg:'成功',data:{{model:{{IntentionCode:'{0}',HouseAddress:'{1}',BillCode:'{2}',GetedMoney:'{3}'}}}}}}", baseinfo.IntentionCode, baseinfo.HouseAddress, info.BillCode, info.GetedMoney));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }
    
    //查询意向金
    private void GetList(HttpContext context)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(" (1=1) ");
        //权限
        //if (CurrentUserInfo.ContainsPermit(Constants.Permit_Money_Search_All))
        //{
        //    sb.Append(" (1=1) ");
        //}
        //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Money_Search_City))
        //{
        //    sb.AppendFormat(" (GetedCityId='{0}') ", CurrentUserInfo.CityId.ToString());
        //}
        //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Money_Search_Company))
        //{
        //    sb.AppendFormat(" (GetedCompanyId='{0}') ", CurrentUserInfo.CompanyId.ToString());
        //}
        //else if (CurrentUserInfo.ContainsPermit(Constants.Permit_Money_Search_Depart))
        //{
        //    sb.Append(" EXISTS(");
        //    sb.Append(string.Format("Select 1 from t_Business_EmpSetting M WHERE a.GetedDepartId=M.DepartId And M.Userid= '{0}' and SearchMoney=1", CurrentUserInfo.UserId.ToString()));
        //    sb.Append(") ");
        //}
        //else
        //    sb.AppendFormat(" (GetedEmployeeId='{0}') ", CurrentUserInfo.UserId.ToString());
        
        //排序
        string strOrderField = "a.Addtime desc";
        if (!string.IsNullOrEmpty(context.Request.Params["sort"]))
            strOrderField = context.Request.Params["sort"];

        //查询条件
        if (!string.IsNullOrEmpty(context.Request["type"]))
        {
            if (context.Request["type"].ToString() == "2")
                sb.Append(" and inorout=1 ");
            else if (context.Request["type"].ToString() == "3")
                sb.Append(" and inorout=0 ");
        }
        if (!string.IsNullOrEmpty(context.Request["Status"]))
        {
            sb.AppendFormat(" and a.Status = '{0}'", context.Request["Status"]);
        }
        if (!string.IsNullOrEmpty(context.Request["starttime"]))
        {
            sb.AppendFormat(" and a.GetedTime >= '{0}'", context.Request["starttime"]);
        }
        if (!string.IsNullOrEmpty(context.Request["endtime"]))
        {
            sb.AppendFormat(" and a.GetedTime <= '{0}'", context.Request["endtime"]);
        }
        if (!string.IsNullOrEmpty(context.Request["AccountType"]))
        {
            sb.AppendFormat(" and a.AccountType='{0}'", context.Request["AccountType"]);
        }
        if (!string.IsNullOrEmpty(context.Request["IsConfirmed"]))
        {
            sb.AppendFormat(" and a.IsConfirmed='{0}'", context.Request["IsConfirmed"]);
        }
        if (!string.IsNullOrEmpty(context.Request["bCustody"]))
        {
            sb.AppendFormat(" and a.bCustody='{0}'", context.Request["bCustody"]);
        }
        if (!string.IsNullOrEmpty(context.Request["PayedTo"]))
        {
            sb.AppendFormat(" and a.PayTo='{0}'", context.Request["PayedTo"]);
        }
        if (!string.IsNullOrEmpty(context.Request["keyword"]))
        {
            sb.AppendFormat(" and (a.IntentionCode like '%{0}%' or b.HouseCode like '%{0}%' or a.BillCode like '%{0}%')", context.Request["keyword"]);
        }

        //查询5级
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
        Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

        if (employee != Guid.Empty)
        {
            sb.AppendFormat(" and a.GetedEmployeeId = '{0}'", employee);
        }
        else if (departs != Guid.Empty)
        {
            sb.AppendFormat(" and a.GetedDepartId = '{0}'", departs);
        }
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null)
            {
                context.Response.Write(retExecResult(Constants.ExecResult.Error, "获取商圈或分类数据丢失", ""));
            }
            sb.AppendFormat(" and (a.GetedDepartId in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
        }
        else if (company != Guid.Empty)
        {
            sb.AppendFormat(" and a.GetedCompanyId = '{0}'", company);
        }
        else if (city != Guid.Empty)
        {
            sb.AppendFormat(" and a.GetedCityId = '{0}'", city);
        }
        else
        {
            sb.AppendFormat(" and a.GetedCompanyId = '{0}'", CurrentUserInfo.CompanyId);
        }

        try
        {
            //条件
            string strWhere = sb.ToString();
            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
            //欲选择字段列表 
            string FieldList = "BillId,IntentionId,IntentionCode,GetedCompany,bussiness,GetedDepart,GetedEmployee,HouseAddress,AccountType,BillCode,CustomerName_Buy,CustomerName_Sale,GetedTime,GetedMoney,FirstMoney,TotalMoney,IsConfirmed,ConfirmEmployee,ConfirmDate,bCustody,Addtime,AddEmployee,Status,InOrOut,PayTo,IsReview,ReviewDate,ReviewEmployee";
            //子查询欲选择字段列表
            string TableFieldList = "a.BillId,a.IntentionId,a.IntentionCode,a.GetedCompany,dbo.FN_GetBussinessByDepartID(a.GetedDepartId) as bussiness,a.GetedDepart,a.GetedEmployee,b.HouseAddress,AccountType,a.BillCode,CustomerName_Buy,CustomerName_Sale,GetedTime,a.GetedMoney,FirstMoney,TotalMoney,a.IsConfirmed,a.ConfirmEmployee,a.ConfirmDate,a.bCustody,a.Addtime,a.AddEmployee,a.Status,InOrOut,PayTo,IsReview,ReviewDate,ReviewEmployee";
            //所要查询的表名
            string TableName = "t_Intention_BillGetedInfo as a inner join t_Intention_BaseInfo as b on a.IntentionId=b.IntentionId";
            //根据sql执行查询
            DataSet ds = Chenxin.Lib.Business.DAL.t_Intention_BaseInfo.GetList(strPageIndex, strPageSize, strOrderField, TableName, strWhere, FieldList, TableFieldList, true);

            context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    //*******************************************
    //功能概要       ：自定义权限检查
    //参数説明       ：strMsg 消息 
    //返回值説明     ：有无权限
    //功能詳細       ：自定义权限检查
    //作成者         ：tianno
    //作成日         ：2010-09-19
    //*******************************************
    public override bool CustomerCheckPermint(HttpContext context, out string strMsg)
    {
        string op = context.Request["op"].ToLower();
        if (op != null)
        {
            if (op.Equals("checkpermit"))
            {
                string Code = context.Request.Params["code"];
                switch (Code)
                {
                    //开单作废
                    case "cancelmove":
                        string modelid = context.Request.Params["modelid"];
                        Chenxin.Lib.Business.Entity.t_Intention_BillGetedInfo getinfo = Chenxin.Lib.Business.DAL.t_Intention_BillGetedInfo.GetModel(new Guid(modelid));
                        if (getinfo.IsConfirmed)
                        {
                            strMsg = "{success:1,msg:'该单据已确认，不可进行作废操作！',data:{permit:false}}";
                            return true;
                        }
                        else if (getinfo.Status == -1)
                        {
                            strMsg = "{success:1,msg:'该单据已作废，不可进行作废操作！',data:{permit:false}}";
                            return true;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        strMsg = "{success:1,msg:'',data:{permit:true}}";
        return true;
    }
}